<template>
  <div class="framework1">
    <div class="framework2">
      <div style="height:calc(100% - 40px);">
        <div class="header">摊位管理->管理人员</div>
        <div class="button_group">
          <el-button type="primary" icon="DocumentAdd" @click="addItem" style="margin-right: 5px"
            v-if="permissionIsShow.add">新增</el-button>
          <el-select v-model="searchRole" placeholder="请选择角色" style="width: 200px;margin-right: 5px" clearable>
            <el-option label="市场监管人员" value="1"></el-option>
            <el-option label="执法人员" value="2"></el-option>
          </el-select>
          <el-input v-model="search" placeholder="姓名、手机号" style="width: 250px;margin-right: 5px" clearable />
          <el-button type="primary" icon="Search" style="margin-left: 5px" @click="reqData">搜索</el-button>
        </div>

        <el-table :data="tableData" :header-cell-style="{ background: '#f4f3f9' }" highlight-current-row
          style="width:100%;height:calc(92vh - 145px);background:#f4f3f9" border>
          <el-table-column align="center" prop="role" label="角色">
            <template v-slot="scope">
              <span v-if="scope.row.role === '1'">市场监管人员</span>
              <span v-else-if="scope.row.role === '2'">执法人员</span>
              <span v-else>未知角色</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="姓名"></el-table-column>
          <el-table-column align="center" prop="phone" label="手机号"></el-table-column>
          <el-table-column align="center" prop="operate" label="操作" fixed="right" width="200"
            v-if="permissionIsShow.edit || permissionIsShow.delete">
            <template v-slot="scope">
              <el-button type="primary" size="small" icon="Edit" @click.native.stop="editItem(scope.row)"
                v-if="permissionIsShow.edit" style="margin-left: 5px;">编辑</el-button>
              <el-button type="danger" size="small" icon="Delete" @click.native.stop="deleteItem(scope.row)"
                v-if="permissionIsShow.delete" style="margin-left: 5px;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="footer">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20]"
          :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 新增和编辑弹窗 -->
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="dialogVisible" width="50%" :close-on-click-modal="false"
      :before-close="handleBeforeClose" @close="closeDialog">
      <div v-loading="submitLoading" element-loading-text="正在保存中，请稍候..." element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="150px">
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%;">
              <el-option label="市场监管人员" value="1"></el-option>
              <el-option label="执法人员" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" clearable></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" clearable></el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: right;">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button type="default" @click="closeDialog">取消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>


<script>
import request from "@/utils/request";
import { Plus } from '@element-plus/icons-vue';
import { stallIp } from "@/ipConfig/stallConfig";
export default {
  name: "StallUser",
  components: {
    Plus
  },
  data() {
    return {
      stallIp: stallIp,
      search: '',
      searchRole: '',
      currentPage: 1, //页码
      pageSize: 10, //页长
      total: 0,
      tableData: [],

      dialogVisible: false,
      isEdit: false,
      submitLoading: false,


      form: {
        id: '',
        role: '',
        phone: '',
        name: '',
      },
      rules: {
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      },

      // 登录用户信息
      loginUserInfo: {
        id: '',
        responsibleScope: '', //查询范围
        roleLevel: '', //角色等级
        unitId: '', //内设部门ID
        userRole: '', //角色ID
        permissions: [], // 按钮路径（数据库中的path）
      },
      // 按钮权限
      permissionIsShow: {
        add: false,
        edit: false,
        delete: false,
      },
    }
  },
  created() {
    const info = JSON.parse(localStorage.getItem("user"));
    this.loginUserInfo = {
      id: Number(info.id),
      responsibleScope: info.responsibleScope, //查询范围
      roleLevel: Number(info.roleLevel),
      unitId: Number(info.unitId),
      userRole: Number(info.userRole),
      permissions: info.permissions.filter(item => Number(item.menuId) === 43).map(item => item.path),
    }
    this.permissionIsShow = {
      add: this.loginUserInfo.permissions.includes('stallUser-add'),
      edit: this.loginUserInfo.permissions.includes('stallUser-edit'),
      delete: this.loginUserInfo.permissions.includes('stallUser-delete'),
    }
    this.reqData(); //加载摊位数据
  },
  methods: {
    reqData() {
      request.get("/stall-related-user/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search,
          searchRole: this.searchRole,
        }
      }).then(res => {
        if (res.code === "200") {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      })
    },
    // 分页功能1
    handleSizeChange(val) {
      this.pageSize = val;
      this.reqData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reqData();
    },
    // 新增摊位
    addItem() {
      this.form = {
        id: '',
        role: '',
        phone: '',
        name: '',
      }
      this.isEdit = false;
      this.dialogVisible = true;
    },
    // 编辑摊位
    editItem(item) {
      this.form = { ...item }
      this.isEdit = true;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.$refs.formRef.resetFields();
      this.dialogVisible = false;
    },
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          const fromData = { ...this.form }
          request.post("/stall-related-user/edit", fromData).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.submitLoading = false;
              this.dialogVisible = false;
              this.reqData();
            } else if (res.code === '500') {
              this.$message.error(res.msg);
              this.submitLoading = false;
            } else {
              this.$message.error("保存失败");
              this.submitLoading = false;
            }
          })
        } else {
          this.$message.error('请填写完整信息');
          return;
        }
      })
    },
    deleteItem(item) {
      this.$confirm('确定删除该管理人员吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/stall-related-user/delete/" + item.id).then(res => {
          if (res.code === '200') {
            this.$message.success('删除成功');
            this.reqData();
          } else {
            this.$message.error("删除失败");
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBeforeClose(done) {
      if (this.submitLoading) {
        // 如果正在提交，不允许关闭
        return;
      }
      // 允许关闭，调用done()触发关闭逻辑
      done();
    },
  }
}
</script>

<style scoped>
/*   外框架   */
.framework1 {
  height: calc(100vh - 88px);
  width: calc(100vh - 200px);
  margin-left: 8px;
  border: solid 1px #D3D3D3;
}

/*   文书内框架   */
.frameworkIn1 {
  height: calc(100vh - 92px);
  width: 100%;
  border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
  height: calc(100vh - 92px);
  border: solid 1px #D3D3D3;
}

/*   文书标题   */
.templateHeader {
  font-size: 19px;
  font-weight: bold;
  padding: 4px 20px;
  height: 30px;
  border: 1px solid #CCCCCC;
  background-color: #E0ECFF;
}

/*   文书底边   */
.templateFooter {
  text-align: center;
  margin-top: -4px;
  padding: 4px 20px;
  height: 30px;
  border: 1px solid #CCCCCC;
  background-color: #E0ECFF;
}

/*   表格大标题   */
.header {
  font-size: 16px;
  font-weight: bold;
  padding: 4px 20px;
  background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
  padding: 4px 10px;
  background-color: #DDDDDD;
}

/*   表格翻页   */
.footer {
  padding: 4px 10px;
  background-color: #f4f3f9;
}

::v-deep .el-table__body tr.current-row>td {
  background: rgb(209, 236, 253) !important;
}
</style>
